﻿using System;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Linq.Expressions;
using System.ComponentModel;

namespace MVVMFramework.Ria.Helpers
{
    internal static class EntityQueryHelper<T>
        where T : Entity
    {
        /// <summary>
        /// Builds the sort query for the key properties for a specified entity like query = query.OrderBy((e) => e.[keyMemberName])
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static EntityQuery<T> BuildSortQueryForEntityKeys(EntityQuery<T> query)
        {
            var keyProperties = typeof(T).GetProperties().Where(
                p => (p.GetCustomAttributes(typeof(KeyAttribute), false).Length > 0)).ToArray();

            var isFirst = true;
            foreach (var p in keyProperties)
            {
                query = BuildSortQueryForEntityKey(query, p, isFirst);
                isFirst = false;
            }

            return query;
        }

        /// <summary>
        /// Builds the sort query for entity key.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="keyProperty">The key property.</param>
        /// <param name="isFirst">if set to <c>true</c> [is first].</param>
        /// <returns></returns>
        private static EntityQuery<T> BuildSortQueryForEntityKey(EntityQuery<T> query, PropertyInfo keyProperty, bool isFirst)
        {
            var entityParam = Expression.Parameter(typeof(T), "e");
            var propertyInfo = keyProperty;
            var memberAccess = Expression.MakeMemberAccess(entityParam, propertyInfo);

            var getQueryMethod = typeof(EntityQueryHelper<T>).GetMethod("GetSortQuery").MakeGenericMethod(propertyInfo.PropertyType);
            var lambdaExpression = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(T), propertyInfo.PropertyType), memberAccess, entityParam);
            var sd = new SortDescription(propertyInfo.Name, ListSortDirection.Ascending);
            query = (EntityQuery<T>)getQueryMethod.Invoke(null, new object[] { query, lambdaExpression, sd, isFirst });

            return query;
        }

        /// <summary>
        /// Builds the sort query for sort descriptions.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="sortDescriptions">The sort descriptions.</param>
        /// <returns></returns>
        public static EntityQuery<T> BuildSortQueryForSortDescriptions(EntityQuery<T> query, SortDescriptionCollection sortDescriptions)
        {
            var isFirst = true;
            foreach (var sd in sortDescriptions)
            {
                query = BuildSortQuery(query, sd, isFirst);
                isFirst = false;
            }
            return query;
        }

        /// <summary>
        /// Builds the sort query for a specified SortDescription like query = query.OrderBy((e) => e.[memberName])
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="sd">The sd.</param>
        /// <param name="isFirst">if set to <c>true</c> [is first].</param>
        /// <returns></returns>
        private static EntityQuery<T> BuildSortQuery(EntityQuery<T> query, SortDescription sd, bool isFirst)
        {
            var entityParam = Expression.Parameter(typeof(T), "e");

            var memberAccess = ReflectionHelper.GetPropertyPathMemberExpression(typeof(T), entityParam, sd.PropertyName);
            var propertyInfo = typeof(T).GetPropertyInfo(sd.PropertyName);
            //PropertyInfo propertyInfo = typeof(T).GetMember(sd.PropertyName)[0] as PropertyInfo;
            //MemberExpression memberAccess = Expression.MakeMemberAccess(entityParam, propertyInfo);

            var getQueryMethod = typeof(EntityQueryHelper<T>).GetMethod("GetSortQuery").MakeGenericMethod(propertyInfo.PropertyType);
            var lambdaExpression = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(T), propertyInfo.PropertyType), memberAccess, entityParam);
            query = (EntityQuery<T>)getQueryMethod.Invoke(null, new object[] { query, lambdaExpression, sd, isFirst });

            return query;
        }


        /// <summary>
        /// Gets the sort query.
        /// Nota: tem que ser public porque é chamado por reflection!
        /// </summary>
        /// <typeparam name="TSortType">The type of the sort type.</typeparam>
        /// <param name="query">The query.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="sd">The sd.</param>
        /// <param name="isFirst">if set to <c>true</c> [is first].</param>
        /// <returns></returns>
        public static EntityQuery<T> GetSortQuery<TSortType>(EntityQuery<T> query, Expression<Func<T, TSortType>> expression, SortDescription sd, bool isFirst)
        {
            if (isFirst)
            {
                return sd.Direction == ListSortDirection.Ascending ? query.OrderBy(expression) : query.OrderByDescending(expression);
            }
            return sd.Direction == ListSortDirection.Ascending ? query.ThenBy(expression) : query.ThenByDescending(expression);
        }
    }
}
